<template>
  <div id="app">
    <keep-alive exclude="App,ChinaEcharts,Chat,module">
      <router-view></router-view>
    </keep-alive>
    <mini-play></mini-play>
    <transition name="panel">
      <play-panel v-if="showPanel"></play-panel>
    </transition>
    <toolbar></toolbar>
    <lyrics v-if="getShowLyrics"></lyrics>
    <transition name="fade">
      <play v-if="showPlay"></play>
    </transition>
    <transition name="mp">
      <message-panel v-if="showMP"></message-panel>
    </transition>
  </div>
</template>
<script>
import MiniPlay from './components/miniPlay/MiniPlay'
import PlayPanel from './components/playPanel/PlayPanel'
import Lyrics from './components/audio/lyrics'
import Play from './components/play/Play'
import toolbar from './components/toolbar/toolbar'
import MessagePanel from './components/messagePanel/MessagePanel'
import request from './api/request'

import { mapGetters } from 'vuex'
export default {
  name: 'App',
  data() {
    return {
      showPlay: false,
      showPanel: false,
      path: '',
      showMP: false
    }
  },
  computed: {
    // vue辅助函数
    ...mapGetters(['getShowLyrics', 'getChatId', 'getPrivateChat', 'getToken'])
  },
  // socket.io相关事件
  sockets: {
    //这里是监听connect事件
    connect: function () {
      // console.log("链接服务器")
    },
    // 监听断开连接，函数
    disconnect() {
      // console.log("断开服务器连接")
    },
    // 操作
    operation() {
      this.getUserInfo()
    },
    // 群信息
    groupNotice(data) {
      this.$store.commit('updateGroupChat', [data.user])
      this.$store.commit('updateUsers', data.users)
      this.$EventBus.$emit('refresh')
    },
    // 系统通知
    systemInforms(data) {
      this.$notify({
        title: '系统通知',
        message:
          '用户：' +
          data.userName +
          ' 由于执行了违规操作已被博主禁言,请其他用户遵守聊天规则',
        type: 'warning'
      })
    },
    // 接收信息
    async receiveMsg(data) {
      if (data.chatType == 'group') {
        let arr = []
        arr.push(data)
        this.$store.commit('updateGroupChat', arr)
      } else {
        this.$EventBus.$emit('updateDialogue', data)
        let arr = this.getPrivateChat[data.account]
        if (!arr) {
          let res = await request({
            url: '/chat/obtain',
            data: {
              chatType: 'private',
              account: data.account,
              token: this.getToken
            },
            method: 'get'
          })
          if (res.msg_list) {
            this.$store.commit('updatePrivateChat', {
              account: data.account,
              msg_list: res.msg_list
            })
          }
        }
        if (arr && arr.length > 0) {
          let prev = new Date(arr[arr.length - 1].date).getTime()
          let current = new Date(data.date).getTime()
          let distant = (current - prev) / 1000 / 60
          distant >= 2 ? (data.showTime = true) : (data.showTime = false)
        }
        let Obj = {
          account: data.account,
          date: data.date,
          message: data.message,
          type: data.type,
          showTime: data.showTime
        }
        this.$store.commit('updatePrivateChat', {
          account: data.account,
          msg_list: [Obj]
        })
        if (data.account == this.getChatId) {
          this.$EventBus.$emit('addMsg', Obj)
        }
      }
    },
    // 评论通知
    notice(data) {
      let { type } = data
      this.$store.commit('updatePrompt', { type, flag: true })
    }
  },
  async created() {
    this.$EventBus.$on('showPanel', () => {
      this.showPanel = !this.showPanel
    })

    this.$EventBus.$on('messagePanel', () => {
      this.showMP = !this.showMP
    })

    this.getFile()
    // console.log(
    //   "IP地址:" +
    //     returnCitySN["cip"] +
    //     ", CID:" +
    //     returnCitySN["cid"] +
    //     ", 地区:" +
    //     returnCitySN["cname"]
    // )

    // 音乐播放列表
    const state = JSON.parse(window.localStorage.getItem('musicState'))
    if (state) {
      this.$store.commit('pushlist', state)
    } else {
      this.$store.commit('pushlist', {})
    }

    this.$store.commit('initSocket', this.$socket) // 初始化socket

    // token
    const blogToken = JSON.parse(window.localStorage.getItem('blogToken'))

    if (blogToken) {
      let { date, token, isTourists } = blogToken
      // 检测用户账号是否存在
      let result = await request({
        url: '/user/time/refresh',
        data: { token },
        method: 'post'
      })
      if (result.status) {
        //判断token的存储时间，并根据时间来判断是否需要更新
        let distance =
          (new Date().getTime() - new Date(date).getTime()) /
          1000 /
          60 /
          60 /
          24
        if (distance > 5 && distance < 7) {
          let res = await request({
            url: '/user/token/refresh',
            data: {
              token
            },
            methods: 'post'
          })
          if (res.status) {
            window.localStorage.setItem(
              'blogToken',
              JSON.stringify({ token: res.token, date: new Date(), isTourists })
            )
            // 更新token
            this.$store.commit('saveToken', res.token)
            this.$store.commit('changeIsLogin', true)
          }
        } else if (distance > 7) {
          if (!isTourists) {
            window.localStorage.removeItem('blogToken')
            this.$store.commit('saveToken', null)
            this.$store.commit('changeIsLogin', false)
          }
        } else {
          this.$store.commit('saveToken', token)
          if (!isTourists) {
            this.$store.commit('changeIsLogin', true)
          }
        }

        let res = await request({
          url: '/find/file',
          data: { token: this.getToken },
          method: 'get'
        })
        this.$store.commit('saveUser', res) // 存储user信息
        this.$store.commit('updateMute', res.mute) // 用户是否被禁言
        this.$store.dispatch('SOCKET_USER_INFO') // socket连接

        if (!res.isAdmin) {
          // this.record()
        }
      } else {
        // 用户账号被清理，清除掉本地保存的token
        window.localStorage.removeItem('blogToken')
      }
    } else {
      this.record()
    }

    this.$EventBus.$on('changeShowPlay', () => {
      //更改Play组件的显示和隐藏
      this.showPlay = !this.showPlay
    })
  },
  components: {
    MiniPlay,
    PlayPanel,
    Lyrics,
    Play,
    toolbar,
    MessagePanel
  },
  watch: {
    $route(to, from) {
      if (this.path == '') {
        this.path = from.path
      } else {
        this.path = to.path
      }
      this.$store.commit('updatePath', this.path)
    }
  },
  mounted() {
    window.addEventListener('beforeunload', () => {
      this.$store.dispatch('SOCKET_LOGOUT') // 注销socket.io的登陆状态
    })

    var w = document.documentElement.scrollWidth || document.body.scrollWidth
    if (w < 600) {
      this.$notify({
        title: '警告',
        message: '想体验更多功能？请在PC端访问',
        type: 'warning',
        duration: 0
      })
    } else {
      // this.$notify({
      //   title: '提示',
      //   message:
      //     '由于阿里云的服务器即将到期，网站迁移至 http://www.yemengshen.cn',
      //   duration: 0,
      //   type: 'warning'
      // })
    }
  },
  methods: {
    // 获取博主个人信息
    async getFile() {
      let res = await request({
        url: '/find/file',
        data: { isAdmin: true },
        method: 'get'
      })
      this.$store.commit('upDateAdmin', res)
      this.userName = res.userName
      this.imageUrl = res.photo
    },
    async record() {
      // 访客记录
      let res = await request({
        url: '/access/record',
        data: {
          ip: returnCitySN['cip'],
          cname: returnCitySN['cname']
        },
        method: 'post'
      })
    },
    async getUserInfo() {
      // 获取token用户的信息
      let res = await request({
        url: '/find/file',
        data: { token: this.getToken },
        method: 'get'
      })
      this.$store.commit('saveUser', res) // 存储user信息
      this.$store.commit('updateMute', res.mute)
    }
  }
}
</script>

<style lang="scss" scoped>
#app {
  height: 100%;
  width: 100%;
}

.panel-enter-active,
.panel-leave-active {
  transition: all 0.8s;
}
.panel-enter,
.panel-leave-to {
  transform: translateX(100%);
  opacity: 0;
}
.fade-enter-active,
.fade-leave-active {
  transition: all 1s;
}
.fade-enter,
.fade-leave-to {
  transform: translate(-100vw, 100vh) scale(0);
  opacity: 0;
}
.mp-enter-active,
.mp-leave-active {
  transition: all 0.8s;
}
.mp-enter,
.mp-leave-to {
  opacity: 0;
}
</style>
